import { defineStore } from 'pinia';

export const useUiStore = defineStore('ui', {
  state: () => ({
    isLoadingApp: false,
    appError: null, // string | null
    logEntries: [], // LLMLogEntrySummaryModel[]
    logDetail: null, // LLMLogEntryModel | null
    logCurrentPage: 1,
    logTotalPages: 1,
    isLogLoading: false,
  }),
  actions: {
    setLoadingApp(loading) {
      this.isLoadingApp = loading;
    },
    setAppError(error) {
      this.appError = error;
    },
    setLogPagingInfo(currentPage, totalPages) {
      this.logCurrentPage = currentPage;
      this.logTotalPages = totalPages;
    },
    clearAgentLogDetail() {
      this.logDetail = null;
    },
    async fetchAgentLogs(agentId, page = 1) {
      if (!agentId) {
        this.appError = 'Agent ID is required to fetch logs.';
        return;
      }
      this.isLogLoading = true;
      this.appError = null;
      try {
        const response = await window.pywebview.api.get_llm_agent_private_logs(agentId, page);
        if (response.success && response.data) {
          this.logEntries = response.data.logs || [];
          this.logCurrentPage = response.data.current_page || 1;
          this.logTotalPages = response.data.total_pages || 1;
          this.logDetail = null; // Clear detail when fetching list
        } else {
          this.appError = response.error_message || 'Failed to fetch agent logs.';
          this.logEntries = [];
          this.logCurrentPage = 1;
          this.logTotalPages = 1;
        }
      } catch (error) {
        console.error('Error fetching agent logs:', error);
        this.appError = `Error fetching agent logs: ${error.message || 'Unknown error'}`;
        this.logEntries = [];
        this.logCurrentPage = 1;
        this.logTotalPages = 1;
      } finally {
        this.isLogLoading = false;
      }
    },
    async fetchAgentLogDetail(logEntryId) {
      if (!logEntryId) {
        this.appError = 'Log Entry ID is required to fetch log details.';
        return;
      }
      this.isLogLoading = true;
      this.appError = null;
      try {
        const response = await window.pywebview.api.get_llm_agent_private_log_entry_details(logEntryId);
        if (response.success && response.data) {
          this.logDetail = response.data.log_details || null;
        } else {
          this.appError = response.error_message || 'Failed to fetch log details.';
          this.logDetail = null;
        }
      } catch (error) {
        console.error('Error fetching log details:', error);
        this.appError = `Error fetching log details: ${error.message || 'Unknown error'}`;
        this.logDetail = null;
      } finally {
        this.isLogLoading = false;
      }
    },
  },
});